<template>
  <div>
    <!-- 面包屑导航区域 -->
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item><a href="/">商品管理</a></el-breadcrumb-item>
      <el-breadcrumb-item>参数列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片区域 -->
    <el-card class="box-card">
      <!-- 警告提示区域 -->
      <el-alert
        title="注意: 只允许为第三级分类设置相关参数"
        type="warning"
        show-icon
        :closable="false"
      >
      </el-alert>
      <!-- 选择商品分类区域 -->
      <el-row class="mrtop">
        <el-col>
          <span class="demonstration mrright">选择商品分类:</span>
          <el-cascader
            v-model="selectedKeys"
            :options="cateList"
            :props="cascaderProps"
            @change="cateListChanged()"
          ></el-cascader>
        </el-col>
      </el-row>
      <!-- 标签区域 -->
      <el-tabs v-model="activeName" @tab-click="handleTabClick">
        <!-- 添加动态参数的面板 -->
        <el-tab-pane label="动态参数" name="many">
          <!-- 添加参数的按钮 -->
          <el-button
            type="primary"
            size="small"
            :disabled="isBtnDisabled"
            @click="addDialogVisivle = true"
            >添加参数</el-button
          >
          <!-- 动态参数的表格 -->
          <el-table :data="manyTableDate" border stripe>
            <!-- 展开航 -->
            <el-table-column type="expand">
              <template v-slot="{ row }">
                <!-- 循环渲染tag标签 -->
                <el-tag
                  :key="index"
                  v-for="(item, index) in row.attr_vals"
                  closable
                  @close="removeTag(index, row)"
                  >{{ item }}</el-tag
                >
                <!-- 输入文本框 -->
                <el-input
                  class="input-new-tag"
                  v-if="row.inputVisible"
                  v-model="row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(row)"
                  @blur="handleInputConfirm(row)"
                >
                </el-input>
                <!-- 添加的按钮 -->
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(row)"
                  >+ New Tag</el-button
                >
              </template>
            </el-table-column>
            <!-- 索引列 -->
            <el-table-column type="index" label="#"></el-table-column>
            <el-table-column
              prop="attr_name"
              label="参数名称"
            ></el-table-column>
            <el-table-column lable="操作">
              <template v-slot="{ row }">
                <el-button
                  size="mini"
                  type="primary"
                  icon="el-icon-edit"
                  @click="showEditParamsDialog(row.attr_id)"
                  >编辑</el-button
                >
                <el-button
                  size="mini"
                  type="danger"
                  icon="el-icon-delete"
                  @click="DeleteParams(row.attr_id)"
                  >删除</el-button
                ></template
              >
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <!-- 添加静态属性的面板 -->
        <el-tab-pane label="静态属性" name="only">
          <!-- 添加属性的按钮 -->
          <el-button
            type="primary"
            size="small"
            :disabled="isBtnDisabled"
            @click="DynamicDialogVisivle = true"
          >
            添加属性
          </el-button>
          <!-- 静态参数的表格 -->
          <el-table :data="onlyTableDate" border stripe>
            <!-- 展开航 -->
            <el-table-column type="expand">
              <template v-slot="{ row }">
                <!-- 循环渲染tag标签 -->
                <el-tag
                  :key="index"
                  v-for="(item, index) in row.attr_vals"
                  closable
                  @close="removeTag(index, row)"
                  >{{ item }}</el-tag
                >
                <!-- 输入文本框 -->
                <el-input
                  class="input-new-tag"
                  v-if="row.inputVisible"
                  v-model="row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(row)"
                  @blur="handleInputConfirm(row)"
                >
                </el-input>
                <!-- 添加的按钮 -->
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(row)"
                  >+ New Tag</el-button
                >
              </template>
            </el-table-column>
            <!-- 索引列 -->
            <el-table-column type="index" label="#"></el-table-column>
            <el-table-column
              prop="attr_name"
              label="属性名称"
            ></el-table-column>
            <el-table-column lable="操作">
              <template v-slot="{ row }">
                <el-button
                  size="mini"
                  type="primary"
                  icon="el-icon-edit"
                  @click="showEditParamsDialog(row.attr_id)"
                  >编辑</el-button
                >
                <el-button size="mini" type="danger" icon="el-icon-delete"
                  >删除</el-button
                ></template
              >
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-card>

    <!-- 动态参数对话框 -->
    <el-dialog
      :title="'添加' + titleText"
      :visible.sync="addDialogVisivle"
      width="50%"
      @close="addDialogClosed"
    >
      <!-- 表格区域 -->
      <el-form
        :model="addParamsFrom"
        :rules="addParamsRules"
        ref="addParamsRef"
        label-width="100px"
      >
        <el-form-item :label="titleText" prop="attr_name">
          <el-input v-model="addParamsFrom.attr_name"></el-input>
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisivle = false">取 消</el-button>
        <el-button type="primary" @click="addParams">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 修改动态参数对话框 -->
    <el-dialog
      :title="'修改' + titleText"
      :visible.sync="editParamsDialogVisiable"
      width="50%"
      @close="editDialogClosed"
    >
      <!-- 表格区域 -->
      <el-form
        :model="editParamsFrom"
        :rules="editParamsRules"
        ref="editParamsRef"
        label-width="100px"
      >
        <el-form-item :label="titleText" prop="attr_name">
          <el-input v-model="editParamsFrom.attr_name"></el-input>
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisivle = false">取 消</el-button>
        <el-button type="primary" @click="editParams">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      queryList: {
        type: '',
        pagenum: 1,
        pagesize: 2
      },
      // 商品分类列表
      cateList: [],
      // 级联选择框的配置对象
      cascaderProps: {
        // 被选中的id值
        value: 'cat_id',
        // 可以看到的级联选择器名称
        label: 'cat_name',
        // 嵌套子节点名称
        children: 'children'
      },
      // 级联选择框双向绑定到的数组
      selectedKeys: [],
      // 被激活的页签name值
      activeName: 'many',
      // 动态属性的数据
      manyTableDate: [],
      // 静态属性的数据
      onlyTableDate: [],
      // 控制动态参数对话框的显示和隐藏
      addDialogVisivle: false,
      // 动态参数表格数据
      addParamsFrom: {
        attr_name: ''
      },
      // 动态参数表格规则对象
      addParamsRules: {
        attr_name: [
          {
            required: true,
            message: '动态参数名称不能为空',
            trigger: 'blur'
          }
        ]
      },
      // 控制修改参数对话框的显示和隐藏
      editParamsDialogVisiable: false,
      // 修改的表单数据对象
      editParamsFrom: {
        attr_name: ''
      },
      // 修改表单的数据验证规则
      editParamsRules: {
        attr_name: [
          {
            required: true,
            message: '请输入参数名称',
            trigger: 'blur'
          }
        ]
      },
      // 控制按钮和文本框的切换显示
      inputVisible: false,
      // 文本框输入的内容
      inputValue: ''
    }
  },
  methods: {
    async getCateList() {
      // 获取所有商品分类列表
      const { data: res } = await this.$http('categories', this.queryList)
      if (res.meta.status !== 200) {
        return this.$message.error('获取商品列表失败')
      }
      this.$message.success('获取商品列表成功')
      this.cateList = res.data
    },
    // 当级联选择框选择的值发生变化时触发的事件
    async cateListChanged() {
      this.getParamsData()
    },
    // tab 页签点击事件的处理函数
    handleTabClick() {
      this.getParamsData()
    },
    // 获取参数的列表数据
    async getParamsData() {
      // 根据selectedKeys 的长度来判断是否选中的是三级分类
      if (this.selectedKeys.length !== 3) {
        this.selectedKeys = []
        this.manyTableDate = []
        this.onlyTableDate = []
        return
      }
      // 根据所选分类的id和当前所处的面板获取对应的参数
      const { data: res } = await this.$http.get(
        `categories/${this.cateId}/attributes`,
        {
          params: {
            sel: this.activeName
          }
        }
      )
      res.data.forEach(item => {
        item.attr_vals = item.attr_vals ? item.attr_vals.split(',') : []
        // 控制文本框的显示和隐藏
        item.inputVisible = false
        item.value = ''
      })
      console.log(res.data)
      if (res.meta.status !== 200) {
        return this.$message.error('获取面板参数失败')
      }
      this.$message.success('获取面板参数成功')

      if (this.activeName === 'many') {
        this.manyTableDate = res.data
      } else {
        this.onlyTableDate = res.data
      }
    },
    // 监听对话框关闭事件
    addDialogClosed() {
      this.$refs.addParamsRef.resetFields()
    },
    // 添加参数
    addParams() {
      // 表单预校验
      this.$refs.addParamsRef.validate(async isPass => {
        if (!isPass) {
          return this.$message.error('表单预校验不通过')
        }
        this.addParamsFrom.attr_sel = this.activeName

        // 发起用户请求
        const { data: res } = await this.$http.post(
          `categories/${this.cateId}/attributes`,
          this.addParamsFrom
        )
        console.log(res)
        if (res.meta.status !== 201) {
          return this.$message.error('添加参数失败')
        }
        this.$message.success('添加参数成功')
        this.addDialogVisivle = false
      })
    },
    // 显示修改动态参数对话框的显示和隐藏
    async showEditParamsDialog(id) {
      this.editParamsDialogVisiable = true
      // 根据id查询参数
      const { data: res } = await this.$http.get(
        `categories/${this.cateId}/attributes/${id}`,
        {
          attr_sel: this.activeName
        }
      )
      console.log(res)
      if (res.meta.status !== 200) {
        return this.$message.error('查询参数失败')
      }
      this.$message.success('查询参数成功')
      this.editParamsFrom = res.data
    },
    // 隐藏修改对话框时触发的事件
    editDialogClosed() {
      // 重置修改的表单
      this.$refs.editParamsRef.resetFields()
    },
    // 点击按钮修改参数
    editParams() {
      // 表单预验证
      this.$refs.editParamsRef.validate(async isPass => {
        if (!isPass) {
          return this.$message.error('表单与预验证失败')
        }
        // 根据id提交参数
        const { data: res } = await this.$http.put(
          `categories/${this.cateId}/attributes/${this.editParamsFrom.attr_id}`,
          {
            attr_name: this.editParamsFrom.attr_name,
            attr_sel: this.activeName
          }
        )
        if (res.meta.status !== 200) {
          return this.$message.error('提交修改失败')
        }
        this.$message.success('提交修改成功')
        this.editParamsDialogVisiable = false
        this.getParamsData()
      })
    },
    // 点击显示删除参数的对话框
    async DeleteParams(attrId) {
      // 弹出删除参数提示框
      const result = await this.$confirm(
        '此操作将永久删除该参数, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).catch(err => err)
      console.log(result)
      if (result === 'cancel') {
        return this.$message.error('取消了删除操作')
      }
      // 发起删除参数的请求
      const { data: res } = await this.$http.delete(
        `categories/${this.cateId}/attributes/${attrId}`
      )

      if (res.meta.status !== 200) {
        return this.$message.error('删除参数失败')
      }
      this.$message.success('删除参数成功')
      this.getParamsData()
    },
    // 点击删除对应的参数和选项
    removeTag(index, row) {
      row.attr_vals.splice(index, 1)
      this.saveAttrbute(row)
    },
    // 文本框失去了焦点或者按下了 Enter 都会触发
    async handleInputConfirm(row) {
      if (row.inputValue.trim().length === 0) {
        row.inputValue = ''
        row.inputVisible = false
      }
      // 如果没有return说明后续的内容需要做输入处理
      row.attr_vals.push(row.inputValue.trim())
      row.inputValue = ''
      row.inputVisible = false
      this.saveAttrbute(row)
    },
    // 点击按钮显示文本框
    showInput(row) {
      row.inputVisible = true
      // 让文本框自动获得焦点
      // $nextTick 方法的作用, 当页面上的元素被重新渲染之后, 才会指定回调函数中的代码
      this.$nextTick(_ => {
        this.$refs.saveTagInput.$refs.input.focus()
      })
    },
    // 将对tags标签的操作保存到数据库
    async saveAttrbute(row) {
      // 需要发起请求, 保存这次的结果
      const { data: res } = await this.$http.put(
        `categories/${this.cateId}/attributes/${row.attr_id}`,
        {
          attr_name: row.attr_name,
          attr_sel: row.attr_sel,
          attr_vals: row.attr_vals.join(',')
        }
      )
      if (res.meta.status !== 200) {
        return this.$message.error('更新参数失败')
      }
      this.$message.success('更新参数成功')
    }
  },
  created() {
    this.getCateList()
  },
  computed: {
    // 如果按钮被经用返回true, 否则返回false
    isBtnDisabled() {
      if (this.selectedKeys.length !== 3) {
        return true
      }
      return false
    },
    // 当前选中三级分类的Id
    cateId() {
      if (this.selectedKeys.length !== 3) {
        return null
      }
      return this.selectedKeys[this.selectedKeys.length - 1]
    },
    // 动态计算标题的文本
    titleText() {
      if (this.activeName === 'many') {
        return '动态参数'
      } else {
        return '静态属性'
      }
    }
  }
}
</script>

<style lang='less' scoped>
.el-breadcrumb {
  margin-bottom: 20px;
}

.mrtop {
  margin-top: 20px;
}

.mrright {
  margin-right: 20px;
}

.el-tag {
  margin: 10px;
}

.input-new-tag {
  width: 120px;
}
</style>
